<template>
  <div class="merchant-management">
    <ArtTableHeader
      :title="$t('wms.merchant.title')"
      :total="tableData.total"
      @refresh="handleRefresh"
      @add="handleAdd"
    >
      <template #search>
        <WmsMerchantSearch @search="handleSearch" @reset="handleReset" />
      </template>
    </ArtTableHeader>

    <ArtTable
      :columns="columns"
      :data="tableData.list"
      :loading="tableLoading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @selection-change="handleSelectionChange"
    >
      <template #merchantType="{ row }">
        <ElTag :type="getMerchantTypeTag(row.merchantType)">
          {{ getMerchantTypeText(row.merchantType) }}
        </ElTag>
      </template>

      <template #status="{ row }">
        <ElTag :type="row.status === '1' ? 'success' : 'danger'">
          {{ row.status === "1" ? "启用" : "禁用" }}
        </ElTag>
      </template>

      <template #action="{ row }">
        <ElButton type="primary" link @click="handleEdit(row)">编辑</ElButton>
        <ElButton type="danger" link @click="handleDelete(row)">删除</ElButton>
      </template>
    </ArtTable>

    <!-- 新增/编辑弹窗 -->
    <WmsMerchantDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-edit="isEdit"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTable } from "@/composables/useTable";
import { WmsBasicService } from "@/api/wms/basicApi";
import WmsMerchantSearch from "./components/WmsMerchantSearch.vue";
import WmsMerchantDialog from "./components/WmsMerchantDialog.vue";
import type { WMS } from "@/types/wms";

defineOptions({ name: "MerchantManagement" });

// 表格配置
const columns = [
  { type: "selection", width: 50 },
  { prop: "merchantNo", label: "商户编号", width: 120 },
  { prop: "merchantName", label: "商户名称", minWidth: 150 },
  { prop: "merchantType", label: "商户类型", width: 100, slot: "merchantType" },
  { prop: "contact", label: "联系人", width: 100 },
  { prop: "phone", label: "联系电话", width: 120 },
  { prop: "email", label: "邮箱", width: 150 },
  { prop: "address", label: "地址", minWidth: 200 },
  { prop: "status", label: "状态", width: 80, slot: "status" },
  { prop: "createTime", label: "创建时间", width: 160 },
  { prop: "action", label: "操作", width: 120, slot: "action", fixed: "right" },
];

// 使用表格组合式函数
const {
  tableData,
  tableLoading,
  pagination,
  handlePageChange,
  handleSelectionChange,
  refreshTable,
} = useTable<WMS.MerchantInfo>({
  fetchData: (params) => WmsBasicService.getMerchantList(params),
  defaultPageSize: 20,
});

// 搜索参数
const searchParams = ref<WMS.MerchantQueryParams>({});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentRow = ref<Partial<WMS.MerchantInfo>>({});

// 获取商户类型标签
const getMerchantTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    "1": "primary",
    "2": "success",
    "3": "warning",
  };
  return typeMap[type] || "info";
};

// 获取商户类型文本
const getMerchantTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    "1": "供应商",
    "2": "客户",
    "3": "承运商",
  };
  return typeMap[type] || "未知";
};

// 搜索处理
const handleSearch = (params: WMS.MerchantQueryParams) => {
  searchParams.value = params;
  refreshTable(params);
};

// 重置搜索
const handleReset = () => {
  searchParams.value = {};
  refreshTable();
};

// 刷新
const handleRefresh = () => {
  refreshTable(searchParams.value);
};

// 新增
const handleAdd = () => {
  currentRow.value = {};
  isEdit.value = false;
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: WMS.MerchantInfo) => {
  currentRow.value = { ...row };
  isEdit.value = true;
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row: WMS.MerchantInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商户"${row.merchantName}"吗？`,
      "删除确认",
      { type: "warning" },
    );

    await WmsBasicService.deleteMerchant(row.id!);
    ElMessage.success("删除成功");
    refreshTable(searchParams.value);
  } catch (_error) {
    if (_error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 弹窗确认
const handleDialogConfirm = async (formData: WMS.MerchantInfo) => {
  try {
    if (isEdit.value) {
      await WmsBasicService.updateMerchant(formData);
      ElMessage.success("更新成功");
    } else {
      await WmsBasicService.createMerchant(formData);
      ElMessage.success("创建成功");
    }

    dialogVisible.value = false;
    refreshTable(searchParams.value);
  } catch (error) {
    ElMessage.error(isEdit.value ? "更新失败" : "创建失败");
  }
};

// 初始化
onMounted(() => {
  refreshTable();
});
</script>

<style lang="scss" scoped>
.merchant-management {
  padding: 20px;

  :deep(.art-table-header) {
    margin-bottom: 16px;
  }
}
</style>
